package com.nb.protocol.protocol;

import io.netty.channel.Channel;

import java.net.InetSocketAddress;

/**
 * 消息载体.
 * <p>
 * 传输模块与服务模块之间双向数据传输载体:
 * <p>
 * MessageHolder
 * Service Module <----------------> Transport Module
 *
 * @author Yohann.
 */
public class MessageHolder {
    private byte[] remoteAddr;
    private byte[] cpuIdBytes;
    private String cpuId;
    private byte serial;
    private short frame;
    private byte type;
    private byte[] body;

    private InetSocketAddress sender;
    private Channel channel;

    public String getCpuId() {
        return cpuId;
    }

    public void setCpuId(String cpuId) {
        this.cpuId = cpuId;
    }

    public byte getSerial() {
        return serial;
    }

    public void setSerial(byte serial) {
        this.serial = serial;
    }

    public short getFrame() {
        return frame;
    }

    public void setFrame(short frame) {
        this.frame = frame;
    }

    public byte getType() {
        return type;
    }

    public void setType(byte type) {
        this.type = type;
    }

    public byte[] getBody() {
        return body;
    }

    public void setBody(byte[] body) {
        this.body = body;
    }

    public InetSocketAddress getSender() {
        return sender;
    }

    public void setSender(InetSocketAddress sender) {
        this.sender = sender;
    }

    public Channel getChannel() {
        return channel;
    }

    public void setChannel(Channel channel) {
        this.channel = channel;
    }

    public byte[] getRemoteAddr() {
        return remoteAddr;
    }

    public void setRemoteAddr(byte[] remoteAddr) {
        this.remoteAddr = remoteAddr;
    }

    public byte[] getCpuIdBytes() {
        return cpuIdBytes;
    }

    public void setCpuIdBytes(byte[] cpuIdBytes) {
        this.cpuIdBytes = cpuIdBytes;
    }

    @Override
    public String toString() {
        return "MessageHolder{" +
                "cpuId=" + cpuId +
                ", serial=" + serial +
                ", frame=" + frame +
                ", type=" + type +
                ", body='" + byteToBit(body) + '\'' +
                ", sender=" + sender +
                '}';
    }

    private static String byteToBit(byte[] bs) {
        StringBuilder stringBuilder = new StringBuilder(40);
        for (byte b : bs) {
            stringBuilder.append(byteToBit(b));
        }
        return stringBuilder.toString();
    }

    private static String byteToBit(byte b) {
        return ""
                + (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1)
                + (byte) ((b >> 5) & 0x1) + (byte) ((b >> 4) & 0x1)
                + (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1)
                + (byte) ((b >> 1) & 0x1) + (byte) ((b >> 0) & 0x1);
    }
}
